//
//  ScrollView.m
//  scrollecView
//
//  Created by qianfeng on 15/9/29.
//  Copyright (c) 2015年 胡志军. All rights reserved.
//

#import "ScrollView.h"
#import "UIImageView+WebCache.h"


#define kScrentW (self.frame.size.width)
#define kScrentH (self.frame.size.height)
@interface ScrollView ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView * scrollView;
@property (nonatomic, strong) UIPageControl * pageContol;
@property (nonatomic, assign) NSInteger imageCount;

@property (nonatomic, strong) NSMutableArray * imageViewArray;
@property (nonatomic, strong) NSTimer * timer;
@end
@implementation ScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        [self setData];
        [self setUI];
    }
    return self;
}


- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}


#pragma mark  --初始化默认值
- (void)setData {
    self.isPageControling = YES;
    self.isTireming = YES;
    self.pageTinColor = [UIColor whiteColor];
    self.alhap = 1.0;
    self.currentPageTinColor = [UIColor blackColor];
    self.placeHolderImage = @"banner";
    
}



#pragma mark  --刷新数据

- (void)reloadData {
    
    self.pageContol.alpha = self.alhap;
    if (self.isPageControling == NO) {
        self.pageContol.hidden = YES;
    }
    if (self.imageUrlArray ) {
        [self setImageView:_imageUrlArray];
    }else if (self.imageArray) {
        [self setImageView:_imageArray];
    }
}



- (NSMutableArray *)imageUrlArray {
    if (_imageUrlArray == nil) {
        _imageUrlArray = [[NSMutableArray alloc] init];
    }
    return _imageUrlArray;
}
#pragma mark  ---Help
- (void)setUI {
    [self addSubview:self.scrollView];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self addSubview:self.pageContol];
    
}


//判断 数组的个数是否具备轮播的个数 （两个以上才可以轮播）


#pragma mark --添加图片数据
- (void)setImageView:(NSArray *)array {
    self.imageCount = array.count;
    self.pageContol.currentPageIndicatorTintColor = self.currentPageTinColor;
    self.pageContol.pageIndicatorTintColor = self.pageTinColor;
    [self.imageViewArray removeAllObjects];
    if (self.imageCount >= 2) {
        self.imageViewArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < array.count; i++) {
            if (i == 0 ) {
                [self.imageViewArray addObject:array[array.count - 1]];
                [self.imageViewArray addObject:array[i]];
            }else if (i == array.count -1) {
                [self.imageViewArray addObject:array[i]];
                [self.imageViewArray addObject:array[0]];
            }
            else {
                [self.imageViewArray addObject:array[i]];
            }
        }
    }else {
        self.imageViewArray = [[NSMutableArray alloc] initWithArray:array];
        self.isTireming = NO;
        self.pageContol.hidden = YES;
    }
    
    self.scrollView.bounces = NO;
    self.scrollView.contentSize = CGSizeMake(kScrentW * self.imageViewArray.count, self.frame.size.height - 100);
    for (int i = 0; i < self.imageViewArray.count; i++) {
        
        
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * kScrentW, 0, kScrentW, kScrentH)];
        
        imageView.userInteractionEnabled = YES;
        if (self.imageArray) {
            imageView.image = [UIImage imageNamed:self.imageViewArray[i]];
        }
        else if(self.imageUrlArray) {
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageViewArray[i]] placeholderImage:[UIImage imageNamed:self.placeHolderImage] options:SDWebImageRefreshCached progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            }];
            
            
            
        }
        
        [self addTap:imageView];
        [self.scrollView addSubview:imageView];
        self.pageContol.numberOfPages = array.count;
    }
    if (self.imageCount < 2) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }else {
        self.scrollView.contentOffset = CGPointMake(kScrentW, 0);
    }
    
    self.pageContol.currentPage = 0;
    
    
    if (self.isTireming) {
        //开始轮播
        [self startTimer];
    }
    
    
    
}


#pragma mark  ---Events

- (void)addTap:(UIView *)view {
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewDidClick)];
    [view addGestureRecognizer:tap];
}

- (void)imageViewDidClick {
    NSInteger count;
    if (self.imageUrlArray.count >= 2 || self.imageArray.count >= 2) {
        CGPoint p = self.scrollView.contentOffset;
        count = p.x/kScrentW;
        count -= 1;
    }
    else{
        count = 0;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(scrollImageDidDelegate:)]) {
        
        [_delegate scrollImageDidDelegate:count];
    }
}


#pragma mark --UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    
    CGPoint point =  scrollView.contentOffset;
    int pageNumber = point.x/kScrentW;
    if (pageNumber == 0) {
        point.x = (self.imageViewArray.count - 2) * kScrentW;
    }else if (pageNumber == self.imageViewArray.count - 1){
        point.x = kScrentW;
    }
    scrollView.contentOffset = point;
    
    self.pageContol.currentPage = point.x/kScrentW -1;
    
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    
    if (self.isTireming) {
        //开始轮播
        [self startTimer];
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self stopTimer];
    
}

#pragma mark  --NSTimer
- (void)startTimer {
   
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


- (void)stopTimer {
    if (self.timer == nil) {
        return;
    }
    [self.timer invalidate];
    self.timer = nil;
}

- (void)roll {
    
    CGPoint point = self.scrollView.contentOffset;
    point.x += kScrentW;
    int pageNumber = point.x/kScrentW;
    if (pageNumber == 0) {
        point.x = (self.imageViewArray.count - 2) * kScrentW;
    }
    [UIView animateWithDuration:1 animations:^{
        self.scrollView.contentOffset = point;
        
    }];
    if (pageNumber == self.imageViewArray.count -1) {
        point.x = kScrentW;
        self.scrollView.contentOffset = point;
    }
    self.pageContol.currentPage = point.x/kScrentW -1;
    
}

#pragma mark --Getter

- (NSTimer *)timer {
    if (_timer == nil) {
         _timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(roll) userInfo:nil repeats:YES];
    }
    return _timer;
}

- (UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScrentW, kScrentH)];
    }
    return _scrollView;
}


- (UIPageControl *)pageContol {
    if (_pageContol == nil) {
        _pageContol = [[UIPageControl alloc] init];
        _pageContol.center = CGPointMake(self.center.x  , kScrentH - 10);
        
    }
    return _pageContol;
}
@end
